package com.billdimmick.merkabah;

import java.io.Serializable;

import org.apache.commons.lang.Validate;
import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;

/**
 * Encapsulates a message to and from SQS. 
 * @author Bill Dimmick <me@billdimmick.com>
 *
 */
public class Message implements Serializable {
	private static final Log log=LogFactory.getLog(Message.class);
	private static final long serialVersionUID = -6945733408561658304L;

	private final String queue;
	private final String message;
	private String messageId;
	private final String receiptHandle;

	/**
	 * Build a new message.
	 * @param queue the queue name - may not be null or empty
	 * @param message the message - may not be null
	 */
	public Message(final String queue, final String message) {
		this(queue, message, null, null);
	}
	
	/**
	 * Build a new message.
	 * @param queue the queue name - may not be null or empty
	 * @param message the message - may not be null
	 * @param id the message ID from SQS - may be null if this message is not from SQS
	 * @param receiptHandle the reciept handle from SQS - may be null if this message is not from SQS
	 */
	public Message(final String queue, final String message, final String id, final String receiptHandle) {
		Validate.notEmpty(queue, "Queue name cannot be null or empty");
		Validate.notNull(message, "Message body cannot be null.");
		this.queue=queue;
		this.message=message;
		this.messageId=id;
		this.receiptHandle=receiptHandle;
		if (log.isTraceEnabled()) {
			log.trace(String.format("message('%s', '%s', %s, %s)", queue, message, id, receiptHandle)); 
		}
	}
	
	/**
	 * Obtains the queue name
	 * @return a non-empty queue name
	 */
	public String getQueue() {
		return this.queue;
	}
	
	/**
	 * Obtains the message body
	 * @return the body - always non-null
	 */
	public String getMessage() {
		return this.message;
	}
	
	/**
	 * Obtains the message ID
	 * @return the id - may not may not be null
	 */
	public String getMessageId() {
		return this.messageId;
	}

	/**
	 * Sets the message ID.  The message ID cannot be changes once it is set.
	 * @param id the ID to use - may not be null or empty
	 */
	public void setMessageId(final String id) {
		Validate.notEmpty(id, "Message Id cannot be null or empty");
		if (this.messageId==null) {
			this.messageId=id;
		} else {
			throw new IllegalStateException("MessageId already set - refusing to assign new value.");	
		}
	}

	/**
	 * Obtains the receipt handle.
	 * @return the handle - may not may not be null
	 */
	public String getReceiptHandle() {
		return this.receiptHandle;
	}	
}
